package com.xyc.www.gulimall.test.sso.server.controller;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.UUID;

@Controller
public class LoginController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/login.html")
    public String login(@RequestParam("redirect_url") String url,
                        Model model,
                        @CookieValue(value = "sso_token", required = false) String sso_token) {
        if (!StringUtils.isEmpty(sso_token)) {
            //说明之前有人登录过，给浏览器留下了痕迹
            return "redirect:" + url + "?token=" + sso_token;
        }

        model.addAttribute("url", url);
        return "login";
    }

    @PostMapping("/doLogin")
    public String doLogin(@RequestParam("username") String username,
                          @RequestParam("password") String password,
                          @RequestParam("url") String url,
                          HttpServletResponse response) {
        if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
            //登录成功就跳回到之前的页面

            //把登录成功的用户存起来
            String uuid = UUID.randomUUID().toString().replace("_", "");
            stringRedisTemplate.opsForValue().set(uuid, username);

            response.addCookie(new Cookie("sso_token", uuid));
            return "redirect:" + url + "?token=" + uuid;
        } else {
            //登录失败，展示登录页
            return "login";
        }
    }
}
